const express = require('express')
const router = express.Router()
const pool = require('../pool')
const query = require('../router/utils');
const request = require('request')
const multer = require('multer');
const upload = multer({
    dest: 'image/userInfo/'
})
const axios = require('axios');

const {host} = require('../router/host')
// 封装数据库搜索用户检查是否存在的函数
function isExist(name,password) {
    return new Promise( (resolve, rejects) => {
        let sql = 'select * from userinfo where nickName=? and password=?'
        let ret=query(sql,[name,password])
        resolve(ret)
    })
}
// 登录接口
router.post('/login',async (req, res) => {
    //如果你找不到用户名和密码是这个的数据 就直接放回用户名或密码错误
    let name = req.body.name
    let password = req.body.password
    let ret=await isExist(name,password)
    if(ret.length){
        res.send({code:1,data:ret[0]})
    }else{
        res.send({code:0,data:'can not find'})
    }

})
// 获取所有用户
router.post('/list',async (req,res)=>{
    let {pageNum,pageSize,keywords} = req.body;
    pageNum = pageNum-1;
    let condition = '';
    const param = [pageNum,pageSize];
    const totalParmas=[];
    if(keywords){
        condition = 'where nickName=?';
        param.unshift(keywords)
        totalParmas.unshift(keywords)
    }
    
    let sql=`select id,nickName,avatar,type,sex,open_id from userinfo ${condition} limit ?,?`;
    let ret=await query(sql,param);
    sql = `select count(id) as count from userInfo ${condition}`;
    let [{count}] = await query(sql,totalParmas);
    // console.log()
    res.send({
        code:1,
        data:{
            list:ret,
            totalCount:count
        },
        msg:'success'
    })
})

// 获取一个用户的详情
router.post('/detail',async (req,res)=>{
    let id=req.body.id
    let sql='select nickName,password,id from userinfo where id=?'
    let ret=await query(sql,[id])
    res.send({
        code:1,
        data:ret[0],
        msg:'success'
    })
})

//更新用户密码
router.post('/updateInfo',async (req,res)=>{
    let {id,nickName,password}=req.body
    let sql='UPDATE userinfo SET nickName=?,password=? WHERE id=?'
    let ret=await query(sql,[nickName,password,id])
    if(ret.affectedRows==1){
        res.send({data:null,code:1})
    }else{
        res.send({data:null,code:0})
    }
}) 

// 增加用户函数
function register(key) {
    return new Promise( (resolve, rejects) => {
        let sql = "INSERT INTO userinfo ( nickName,password) VALUES (?,?);"
        let ret=query(sql,key)
        resolve(ret)

    })
}
// 增加用户
router.post('/add',async(req,res)=>{
    let {nickName,password}=req.body
    let ret=await register([nickName,password])
    if(ret.affectedRows==1){
        res.send({data:null,code:1})
    }else{
        res.send({data:null,code:0})
    }
})

// 删除用户
router.post('/del',async(req,res)=>{
    const del=req.body
    let sql=`DELETE  from userinfo where id in (${del.join()})`
    let ret =await query(sql)
    if(ret.affectedRows==1){
        res.send({data:null,code:1})
    }else{
        res.send({data:null,code:0})
    }
})

// 收藏歌曲
router.get('/shoucang', async (req, res) => {
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql = 'INSERT INTO shoucang ( s_id,open_id ,isCate) VALUES (?,?,?); '
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)

})
// 找到收藏的具体的一首歌曲
router.get('/oneshoucang',async (req, res) => {
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql='select * from shoucang where s_id=? and open_id=? and isCate=?';
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)
})
// 删除收藏的歌曲
router.get('/cancleShoucang',async (req,res)=>{
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql='delete from shoucang where s_id=? and open_id=? and isCate=?';
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)

})
// 获取所有收藏的歌曲
router.get('/allShoucang',async (req,res)=>{
    let open_id = req.query.openId
    let page=req.query.page
    let count=7
    let start=(parseInt(page)-1)*count
    let sql=`select s_id,isCate from shoucang where open_id=? limit ${start},${count}`
    const ret = await query(sql,[open_id]);
    const pros = ret.map(ele=>{
        if(ele.isCate==='true'){
            sql='select * from detail where id=?';
        }else{
            sql="select * from zhuanji where id=?"
        }
        return query(sql,[ele.s_id])
    });
    let result = await Promise.all(pros);
    result = result.map(ele=>ele[0])
    res.send({data:result,code:200})
})

module.exports = router